import { createApp, h } from 'vue';
import { Spin } from 'ant-design-vue';

type LoadingOptions = {
  fullscreen?: boolean;
  text?: string;
};

const Loading = {
  show(options?: LoadingOptions) {
    const loadingInstance = createApp({
      render() {
        return h(
          'div',
          {
            style: {
              position: options?.fullscreen ? 'fixed' : 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: 'flex',
              'justify-content': 'center',
              'align-items': 'center',
              'z-index': 9999,
              'background-color': 'rgba(255, 255, 255, 0.5)'
            }
          },
          [
            h(Spin, {
              size: 'large',
              tip: options?.text || '加载中...'
            })
          ]
        );
      }
    });

    const mountNode = document.createElement('div');
    document.body.appendChild(mountNode);
    loadingInstance.mount(mountNode);

    return {
      close: () => {
        loadingInstance.unmount();
        document.body.removeChild(mountNode);
      }
    };
  },
  close() {
    // 关闭所有loading实例
  },
  install(app: any) {
    const loading = {
      show(options?: LoadingOptions) {
        const loadingInstance = createApp({
          render() {
            return h(
              'div',
              {
                style: {
                  position: options?.fullscreen ? 'fixed' : 'absolute',
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  display: 'flex',
                  'justify-content': 'center',
                  'align-items': 'center',
                  'z-index': 9999,
                  'background-color': 'rgba(255, 255, 255, 0.5)'
                }
              },
              [
                h(Spin, {
                  size: 'large',
                  tip: options?.text || '加载中...'
                })
              ]
            );
          }
        });

        const mountNode = document.createElement('div');
        document.body.appendChild(mountNode);
        loadingInstance.mount(mountNode);

        return {
          close: () => {
            loadingInstance.unmount();
            document.body.removeChild(mountNode);
          }
        };
      }
    };

    app.config.globalProperties.$loading = loading;
    app.provide('loading', loading);
  }
};

export default Loading;